/*
 * Copyright 2008-2010 GP Software
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 * DataMerger.java | Created on Sep 28, 2010
 */
package org.gpsoftware.xlsMerge.dataMerger;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.gpsoftware.xlsMerge.FileType;
import org.gpsoftware.xlsMerge.MergeException;
import org.gpsoftware.xlsMerge.ReadException;
import org.gpsoftware.xlsMerge.Row;
import org.gpsoftware.xlsMerge.fileReader.FileReader;
import org.gpsoftware.xlsMerge.fileReader.FileReaderFactory;
import org.gpsoftware.xlsMerge.fileWriter.FileWriter;
import org.gpsoftware.xlsMerge.fileWriter.FileWriterFactory;

import java.io.File;
import java.net.URL;
import java.util.Set;

/**
 * Merges worksheets into a single file and removes duplicates
 *
 * @author Paul Augustine C. Mendoza
 */
class XlsWorksheetDataMerger implements DataMerger {

    private static final String EXTENSION = ".xls";

    private File outputFile;
    private FileReader fileReader;
    private FileWriter fileWriter;

    @SuppressWarnings("unchecked")
    public void merge(File inputFile, String outputFilePrefix) throws
            MergeException {
        try {
            initialize(outputFilePrefix);
            Set<Row<HSSFRow>> data = this.fileReader.read(inputFile);
            this.fileWriter.write(this.outputFile, data);
        } catch (ReadException re) {
            throw new MergeException(re, inputFile);
        } catch (Exception e) {
            throw new MergeException(e, inputFile);
        }
    }

    private void initialize(String outputFileSuffix) {
        URL url = this.getClass().getClassLoader().getResource(".");
        File f = new File(url.getPath());
        this.outputFile = new File(f, outputFileSuffix + EXTENSION);
        this.fileReader = FileReaderFactory.getFileReader(FileType.XLS);
        this.fileWriter = FileWriterFactory.getFileWriter(FileType.XLS);
    }

    public File getOutputFile() {
        return this.outputFile;
    }

}
